package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"pay_srv/models/mysql"
	"pay_srv/models/redis"
	"pay_srv/pkg"
	"strconv"
	"time"

	"pay_srv/internal/svc"
	"pay_srv/pay"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeLogic {
	return &RechargeLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RechargeLogic) Recharge(in *pay.RechargeRequest) (*pay.RechargeResponse, error) {
	// todo: add your logic here and delete this line

	//获取会员信息
	memberInfo, err := redis.GetMemberInfo(int(in.UserId))
	if err != nil {
		return nil, errors.New("获取会员信息失败")
	}

	// 使用会员信息
	s, _ := strconv.Atoi(memberInfo["duration"])
	// 打印会员等级和剩余时长
	//fmt.Printf("会员等级: %s, 剩余时长: %d 天\n", level, remainingDays)
	fmt.Printf("会员剩余时长: %d 天\n", s)
	if s < 5 {
		return nil, errors.New("您的会员不足5天请续费")
	}
	m := mysql.Member{
		UserId:    int(in.UserId),
		Amount:    float64(in.Amount),
		PayType:   in.PayType,
		PayStatus: in.PayStatus,
		PayTime:   time.Now(),
		Duration:  in.Duration,
	}
	err = m.Add()
	if err != nil {
		return nil, errors.New("支付失败")
	}

	var M = make(map[string]interface{})
	M["userId"] = in.UserId
	M["amount"] = in.Amount
	M["payType"] = in.PayType
	M["payStatus"] = in.PayStatus
	M["duration"] = in.Duration
	redis.AddGoods(int(in.UserId), M)
	orderSn := uuid.NewString()
	price := fmt.Sprintf("%.2f", in.Amount)
	pkg.AliPay(orderSn, price)
	return &pay.RechargeResponse{PayStatus: m.PayStatus, OrderSn: orderSn}, nil
}
